package mrusanov.view

import xml.{Node, XML}
import java.io.File
import mrusanov.images.{ImageInfo, Image}
import mrusanov.sounds.SoundConfigLoader

object GraphicEffectInfoLoader {
  private val IMAGES_PATH_PREFIX = "/data/images/effects/"

  lazy val effectsInfo:Map[String, MovingSpriteEffectInfo] = loadEffects

  def loadEffects:Map[String, MovingSpriteEffectInfo] = {
    val path = getClass.getResource("/conf/graphicEffects.xml").toURI
    val xml = XML.loadFile(new File(path))

    var retMap = Map[String, MovingSpriteEffectInfo]()

    (xml \ "effect") foreach(pt => {
      val effectName = (pt \ "@name").toString()
      val startingIndexElement = (pt \ "@index")
      val distanceElement = (pt \ "@distance")
      val distance = if (distanceElement.isEmpty) 1
                      else distanceElement.toString().toDouble
      val endMoveSoundElement = (pt \ "@endMoveSound")
      val endMoveSound = if (endMoveSoundElement.isEmpty) None
          else Some(SoundConfigLoader.soundsMap(endMoveSoundElement.toString()))

      var stagesMap = Map[MovingSpriteEffectStage, Vector[Image]]()

      List(StartMove, Move, EndMove) foreach( st => {
        stagesMap += st -> parseMovingStage(effectName.dropRight(5), pt, st)
      })

      retMap += effectName -> new MovingSpriteEffectInfo(effectName, stagesMap, distance, endMoveSound)
    })

    retMap
  }

  private def parseMovingStage(name:String, node:Node, stage:MovingSpriteEffectStage):Vector[Image] = {
    val retList = for (pt <-(node \ stage.name \ "image")) yield {
      val path = (pt \ "@path").toString()
      new ImageInfo(path, IMAGES_PATH_PREFIX + name).buildImage
    }

    Vector() ++ retList
  }


}
